//
//  KRRecipeListController.m
//  cookBook
//
//  Created by kuroken on 16/1/10.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRRecipeListController.h"
#import <PureLayout.h>
#import "KRRecipeListCell.h"
#import "KRConst.h"
#import "KRRecipeList.h"
#import <MJExtension.h>
#import "KRAlbumInfoController.h"
#import "KRReadPostController.h"
#import "KRRecipeInfoController.h"
#import "KRWebController.h"
#import "KRShareWebviewController.h"

NSUInteger const KRLayoutHeight = 220;
NSUInteger const KRMaxSection = 100;

NSTimeInterval const KRPlayTime = 6.0;

@interface KRRecipeListController ()
@property (nonatomic, weak) UIPageControl *pageControl;
@property (nonatomic, weak) NSTimer *timer;
@end

@implementation KRRecipeListController

/* 初始化布局 */
- (instancetype)init
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(KRLayoutWidth, KRLayoutHeight);
    layout.sectionInset = UIEdgeInsetsZero;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

     return [self initWithCollectionViewLayout:layout];
}

static NSString * const reuseIdentifier = @"recipe";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //** self.collectionView.superview == self.view **//
    
    
//    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(back)];
//    self.navigationItem.leftBarButtonItem = backButton;
    
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    // 设置frame
    self.view.frame = CGRectMake(0, 0, KRLayoutWidth, KRLayoutHeight);
    self.collectionView.frame = CGRectMake(0, 0, KRLayoutWidth, KRLayoutHeight);

    
    // 添加pageControl：分页，展示目前看的是第几页
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.userInteractionEnabled = NO;
    pageControl.numberOfPages = self.recipeList.count;
    pageControl.currentPageIndicatorTintColor = KRColor(254, 98, 43);
    pageControl.pageIndicatorTintColor = KRColor(189, 189, 189);
    [self.view addSubview:pageControl];
    [pageControl autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view];
    [pageControl autoPinEdgeToSuperviewEdge:ALEdgeBottom];
    self.pageControl = pageControl;

    
    self.collectionView.pagingEnabled = YES;
    
//    [self.collectionView registerClass:[KRRecipeListCell class] forCellWithReuseIdentifier:reuseIdentifier];

    // 注册cell
    [self.collectionView registerNib:[UINib nibWithNibName:@"KRRecipeListCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    
    // 默认显示最中间的那组
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:KRMaxSection/2] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    
    
    // 添加定时器
    [self addTimer];
}

/**
 *  添加定时器
 */
- (void)addTimer
{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:KRPlayTime target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
}

- (void)removeTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

/**
 *  显示回最中间那组的数据
 */
- (NSIndexPath *)resetIndexPath
{
    // 获取当前item的位置
    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    
    NSIndexPath *indexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:KRMaxSection/2];
    // 显示回最中间那组的数据
    [self.collectionView scrollToItemAtIndexPath:indexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    return indexPathReset;
}

/**
 *  下一页
 */
- (void)nextPage
{
    // 1.获取当前item的位置
    NSIndexPath *currentIndexPath = [self resetIndexPath];
//    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
   
    // 2.计算下一个item的位置
    NSInteger nextItem = currentIndexPath.item + 1;
    NSInteger nextSection = currentIndexPath.section;
    if (nextItem == self.recipeList.count) {
        nextItem = 0;
        nextSection++;
    }
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    
    // 3.通过动画滚动到下一个item
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

- (void)back
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    double page = scrollView.contentOffset.x / scrollView.width;
    // 四舍五入计算出页码
    self.pageControl.currentPage = (int)(page + 0.5) % self.recipeList.count;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addTimer];
}


#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return KRMaxSection;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.recipeList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
     KRRecipeListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    cell.recipeList = self.recipeList[indexPath.item];
    
    return cell;
}

#pragma mark <UICollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    /*
     haodourecipe://haodou.com/openurlid/?id=553363                         网页
     haodourecipe://haodou.com/openurl/?url=http://img4.hoto.cn/act/2016/01/video/index.html?v=3                                                               视频（网页）
     haodourecipe://haodou.com/opentopic/?url=http%3A%2F%2Fm.haodou.com%2Ftopic-422100.html&id=422100                                     单条阅读
     haodourecipe://haodou.com/collect/info/?id=6059655                     专辑
     haodourecipe://haodou.com/recipe/info/?id=1032518&video=0              单条食谱
     
     
     */

    NSString *jumpUrl = self.recipeList[indexPath.item].url;

    if ([jumpUrl containsPartString:@"opentopic"]) {// 单条阅读
        NSRange range = [jumpUrl rangeOfString:@"id="];
        NSString *topicID = [jumpUrl substringFromIndex:range.length + range.location];
        
        KRReadPostController *readPostVc = [[KRReadPostController alloc] init];
        readPostVc.topicID = topicID;
        [self.navigationController pushViewController:readPostVc animated:YES];
        
    } else if ([jumpUrl containsPartString:@"collect/info"]) {// 专辑
        NSRange range = [jumpUrl rangeOfString:@"id="];
        NSString *albumID = [jumpUrl substringFromIndex:range.length + range.location];
        
        KRAlbumInfoController *infoVc = [[KRAlbumInfoController alloc] init];
        infoVc.albumID = albumID; //专辑ID
        [self.navigationController pushViewController:infoVc animated:YES];
        
    } else if ([jumpUrl containsPartString:@"recipe/info"]) {// 单条食谱
        NSRange range = [jumpUrl rangeOfString:@"id="];
        NSUInteger loc = range.length + range.location;
        NSRange range_and = [jumpUrl rangeOfString:@"&"];
        NSUInteger len = range_and.location - loc;
        NSString *recipeID = [jumpUrl substringWithRange:NSMakeRange(loc, len)];
        
        KRRecipeInfoController *infoVc = [[KRRecipeInfoController alloc] init];
        infoVc.recipeID = recipeID; // RecipeId
        [self.navigationController pushViewController:infoVc animated:YES];
    } else if ([jumpUrl containsPartString:@"openurl/?url"]) { // 视频（网页）
        NSRange urlRange = [jumpUrl rangeOfString:@"url="];
        NSString *url = [jumpUrl substringFromIndex:urlRange.location + urlRange.length];
        
        KRWebController *webVc = [[KRWebController alloc] init];
        webVc.url = url;
        [self.navigationController pushViewController:webVc animated:YES];
    } else if ([jumpUrl containsPartString:@"openurlid"]) { // 网页
        NSRange range = [jumpUrl rangeOfString:@"id="];
        NSString *shareID = [jumpUrl substringFromIndex:range.length + range.location];
        
        KRShareWebviewController *shareWebviewVc = [[KRShareWebviewController alloc] init];
        shareWebviewVc.shareID = shareID;
        [self.navigationController pushViewController:shareWebviewVc animated:YES];
    }
}

@end